package com.renhuikeji.pro.ala.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.renhuikeji.pro.ala.R;
import com.renhuikeji.pro.ala.bean.BasicBean;
import com.renhuikeji.pro.ala.bean.LoginCodeBean;
import com.renhuikeji.pro.ala.config.ConfigValue;
import com.renhuikeji.pro.ala.jpush.JpushUtil;
import com.renhuikeji.pro.ala.utils.CodeUtils;
import com.renhuikeji.pro.ala.config.Constant;
import com.renhuikeji.pro.ala.utils.DealResUtil;
import com.renhuikeji.pro.ala.utils.DialogUtils;
import com.renhuikeji.pro.ala.utils.NetworkManageUtil;
import com.renhuikeji.pro.ala.utils.OkHttpUtils;
import com.renhuikeji.pro.ala.utils.SPUtils;
import com.renhuikeji.pro.ala.utils.StringUtil;
import com.renhuikeji.pro.ala.utils.TimeCount;
import com.renhuikeji.pro.ala.utils.ToastUtils;
import com.renhuikeji.pro.ala.widget.LoadingDialog;

import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


public class RegisterActivity extends BaseActivity {


    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_yzm)
    EditText et_yzm;
    @BindView(R.id.tv_get_yzm)
    TextView tv_get_yzm;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.et_password_again)
    EditText et_password_again;
    @BindView(R.id.checkbox_register)
    CheckBox checkbox_register;
    @BindView(R.id.btn_register)
    TextView btn_register;
    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.et_qq)
    EditText etQq;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.et_code)
    EditText etCode;
    private CodeUtils codeUtils;
    public int res_yzm;
    public LoadingDialog loadingDialog;
    private String baseUrl;
    private String apikey;
    private String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        baseUrl = ConfigValue.APP_IP;
        apikey = ConfigValue.API_KEY;
        initView();
    }

    private void initView() {
        tvMiddleTitle.setText("用户注册");
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        loadingDialog = new LoadingDialog(this, R.style.WhiteDialog);
        codeUtils = CodeUtils.getInstance();
        Bitmap bitmap = codeUtils.createBitmap();
    }

    String phone;

    private void checkPersonalData() {
        phone = et_phone.getText().toString().trim();
        if (!StringUtil.phoneCheck(phone)) {
            showToast("请输入正确的手机号码");
            return;
        }

        String yzm = et_yzm.getText().toString().toString();
        if (StringUtil.isEmpty(yzm)) {
            showToast("请输入短信验证码");
            return;
        }

        String password = et_password.getText().toString();
        if (!StringUtil.passwordCheck(password)) {
            showToast("密码为6-20位大小写字母、符号或数字");
            return;
        }

        String password_again = et_password_again.getText().toString().trim();
        if (StringUtil.isEmpty(password_again)) {
            showToast("请再次输入密码");
            return;
        } else if (!password_again.equals(password)) {
            showToast("两次密码不相同");
            return;
        }
//        String qq = etQq.getText().toString().trim();
//        if (StringUtil.isEmpty(qq)) {
//            showToast("请输入QQ号");
//            return;
//        }
//        String email = etEmail.getText().toString().trim();
//        if (StringUtil.isEmpty(password_again)) {
//            showToast("请输入邮箱");
//            return;
//        }
//        String code = etCode.getText().toString().trim();
//        if (StringUtil.isEmpty(password_again)) {
//            showToast("请输入推广码");
//            return;
//        }

        boolean checked = checkbox_register.isChecked();

        if (!checked) {
            showToast("请阅读并同意《用户服务协议》");
            return;
        }
        requestRegister(phone, password, yzm);
    }


    @OnClick({R.id.btn_register, R.id.tv_get_yzm,R.id.title_left_one_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_register:
                checkPersonalData();
                break;
            case R.id.tv_get_yzm:
                getYzm();
                break;
            case R.id.title_left_one_btn:
                finish();
                break;
        }
    }

    /**
     * 验证码
     */
    String session;

    private void getYzm() {
        phone = et_phone.getText().toString().trim();
        if (!StringUtil.phoneCheck(phone)) {
            showToast("请输入正确的手机号码");
            return;
        }
        if (NetworkManageUtil.isNetworkAvailable(this)) {
            ToastUtils.toastForShort(this, "正在发送...");
        }
        OkGo.<String>post(Constant.BASE_URL + "?g=api&m=member&a=sendCode")
                .params("mobile",phone)
                .params("type",1)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DealResUtil.getInstace().dealBase(RegisterActivity.this,response);
                        TimeCount timeCount=new TimeCount(tv_get_yzm, 120000, 1000);
                        timeCount.start();
                    }
                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(RegisterActivity.this,getString(R.string.bad_net));
                        super.onError(response);
                    }
                });

    }

    /**
     * 注册
     *
     * @param phone
     * @param password
     * @param yzm
     */
    private void requestRegister(String phone, String password, String yzm) {

        requestRegist(phone, password, yzm);
    }

    private void requestRegist(final String phone, final String password, String post_yzm) {
        DialogUtils.showProgressDlg(RegisterActivity.this, getString(R.string.loading));
        OkGo.<String>post(Constant.BASE_URL + "?g=api&m=member&a=register")
                .params("mobile",phone)
                .params("pwd",password)
                .params("code",post_yzm)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BasicBean bean=DealResUtil.getInstace().dealBase(RegisterActivity.this,response);
                        if(bean!=null){
                            if(bean.getStatus()==Constant.SUCCESS){
                                RegisterActivity.this.finish();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(RegisterActivity.this,getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }


    private void setAlias(String name) {
        if (TextUtils.isEmpty(name)) {
            ToastUtils.toastForShort(RegisterActivity.this, "别名不能为空");
            return;
        }
        if (!JpushUtil.isValidTagAndAlias(name)) { //检查格式
            ToastUtils.toastForShort(RegisterActivity.this, "别名格式错误");
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, name));
    }

    private static final int MSG_SET_ALIAS = 1001;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("wch", logs);
                    break;

                case 6002:
                    logs = "别名设置超时，60s后重试";
                    Log.i("wch", logs);
                    if (JpushUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i("wch", "无网络");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("wch", logs);
            }

//            JpushUtil.showToast(logs, getApplicationContext());
        }

    };

    //------------------------------------------------------------
}
